<?php
ArrowController::importModel("org.arrowplatform.controls.forms.IArrowFormValidator");
class ArrowFormDefaultValidator implements IArrowFormValidator{

	const ERROR_LENGTH = 1;
	const ERROR_REGEXP = 2;
	const ERROR_OWN = 3;

	protected $fieldsWithError = array();
	protected $alerts = array();

	public static function getDefault(){
		return new ArrowFormDefaultValidator;
	}

	public function afterCheck() {}

	public function validate( ArrowForm $form, $proposedValues ){
		$this->validationPass = true;
		foreach( $form->getFields() as $field ){
			if( $field->access ) {
				$result = $this->validateField( $field, $proposedValues[$field->getName()] );
				if(!$result)
				$this->validationPass = false;
			}
		}

		$this->afterCheck() ;


		return $this->validationPass;
	}

	private function validateField( IArrowFormField  $field, $proposedValue ){
		$ok = true;
		$this->fieldsValues[$field->getName()] = $proposedValue;
		if( $field->isCheckable() ){
			$length = $field->getProperty("length");
			$this->fieldsWithError[$field->getName()] = array();
			if($length){
				if(empty($proposedValue) && $field->getProperty("checkifempty") ){
					if($this->checkLength( $length, $proposedValue )){
						$this->fieldsWithError[$field->getName()][] = $field->getProperty("alert");
						$ok = false;
					}
				}
			}
			$rexp = $field->getProperty("rexp");
			if($rexp){
				if($this->checkRegExp( $rexp, $proposedValue )){
					$this->fieldsWithError[$field->getName()][] = $field->getProperty("alert");
					$ok = false;
				}
			}
			$selfValidate = $field->validate( $proposedValue );
			if( $selfValidate !== true ){
				if( $selfValidate === false ){
					$this->fieldsWithError[$field->getName()][] = $field->getProperty("alert");
					$ok = false;
				}else{
					$this->fieldsWithError[$field->getName()][] = $selfValidate;
					$ok = false;
				}
			}
			if(empty($this->fieldsWithError[$field->getName()]))
				unset($this->fieldsWithError[$field->getName()]);
		}
		if($ok == false)
			$this->validationPass = false;

		return $ok;
			
	}

	public function getFieldsWithErrors(){
		return $this->fieldsWithError;
	}

	public function addFieldError( $field, $alert ){
		return $this->fieldsWithError[$field][] = $alert;
	}
	
	
	
	
	public function addAlert( $alert ){
		return $this->alerts[] = $alert;
	}
	
	public function getAlerts(){
		return $this->alerts;
	}

	private function checkLength( $fieldLenght, $proposedValue ){
		$length = explode( ",", $fieldLenght );
		if 	(
		( strlen($proposedValue) < $length[0])
		||
		(isset ($length[1]) && ($length[1] && strlen($proposedValue) > $length[1]))
		){
			return true;
		}
		return false;
	}

	private function checkRegExp( $rexp, $proposedValue ){
		if (!preg_match($rexp, $proposedValue))
		return true;
		return false;
	}


}
?>